package com.opi.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

import com.opi.bean.NetworkBean;


public class CommUtil {

	private  static Logger logger = Logger.getLogger(CommUtil.class);

	private static BufferedReader input = null;
	
	/**
	 * 
	 * Description:发送命令
	 * @author: Chen
	 * @date: 2016年10月17日
	 * @param commands
	 * @return
	 */
	public  static String getDiskOrMemoryInfo(String commands){
		String str="";
		try {
			input = exeCmd(commands);
			String line;
			while ((line = input.readLine ()) != null){
				if(line.contains("tmpfs") || line.contains("udev")) continue;
				str += (line+"<br>");
			}
		} catch (Exception e) {
			logger.error ("getDiskOrMemoryInfo:" + e.getMessage());
			return "error";
		}
		return str;
	}
	
	public static String getCpuTempOrLoadInfo(String commands){
		String str="";
		try {
			input = exeCmd(commands);
			String line;
			if ((line = input.readLine ()) != null){
				str += line;
			}
		} catch (Exception e) {
			logger.error ("getCpuTempOrLoadInfo:" + e.getMessage());
			return null;
		}
		return str;
	}
	
	
	/**
	 * 
	 * Description:解析网络数据
	 * @author: 陈维康
	 * @date: 2017年6月29日
	 * @param commands
	 * @return
	 */
	public  static String getNetInfo(String commands){
		String json = "";
		try {
				input = exeCmd(commands);
				String in =  input.readLine ();
				String out = input.readLine ();
				json = "{\"in_net\":\""+in+"\",\"out_net\":\""+out+"\"}";
		} catch (Exception e) {
			logger.error ("getNetInfo:" + e.getMessage());
			json = "{\"in_net\":\"error\",\"out_net\":\"error\"}";
		}
		return json;
	}
	
	public static NetworkBean getNetInfoToBean(String commands){
		NetworkBean bean = null;
		try {
			input = exeCmd(commands);
			String in =  input.readLine ();
			String out = input.readLine ();
			bean = new NetworkBean(in, out, DateUtil.getNowTime(1));
		} catch (Exception e) {
			logger.error (e);
		}
		return bean;
	}
	
	
	public  static String sendCmd(String commends){
		String str = "";
		try {
			Runtime.getRuntime().exec(commends);
		} catch (Exception e) {
			logger.error ("sendCmd:" + e.getMessage());
			return "error";
		}
		return str;
	}
	
	/**
	 * 执行命令
	 * @param cmd
	 * @return
	 * @throws IOException 
	 */
	private static BufferedReader exeCmd(String cmd) throws IOException{
		Process process = Runtime.getRuntime().exec(cmd);
		InputStreamReader ir=new InputStreamReader(process.getInputStream());
		return new BufferedReader (ir);
	}
	
}
